<!doctype html>
<html lang="zh">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>学习计划助手</title>
    <style>
      body {
        font-family: 'Arial', sans-serif;
        max-width: 800px;
        margin: 0 auto;
        padding: 20px;
        background-color: #f5f5f5;
        color: #333;
      }
      h1 {
        text-align: center;
        color: #2c3e50;
      }
      .section {
        background-color: white;
        border-radius: 8px;
        padding: 20px;
        margin-bottom: 20px;
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
      }
      h2 {
        color: #3498db;
        border-bottom: 2px solid #ecf0f1;
        padding-bottom: 10px;
        margin-top: 0;
      }
      .form-group {
        margin-bottom: 15px;
      }
      label {
        display: block;
        margin-bottom: 5px;
        font-weight: bold;
      }
      input,
      textarea {
        width: 100%;
        padding: 8px;
        border: 1px solid #ddd;
        border-radius: 4px;
        box-sizing: border-box;
      }
      button {
        background-color: #3498db;
        color: white;
        border: none;
        padding: 10px 15px;
        border-radius: 4px;
        cursor: pointer;
        font-size: 16px;
        margin-right: 10px;
        transition: background-color 0.3s;
      }
      button:hover {
        background-color: #2980b9;
      }
      button:disabled {
        background-color: #bdc3c7;
        cursor: not-allowed;
      }
      #startButton {
        background-color: #2ecc71;
      }
      #startButton:hover {
        background-color: #27ae60;
      }
      #stopButton {
        background-color: #e74c3c;
      }
      #stopButton:hover {
        background-button: #c0392b;
      }
      .status {
        margin-top: 20px;
        padding: 10px;
        border-radius: 4px;
        text-align: center;
        display: none;
      }
      .info {
        background-color: #d9edf7;
        color: #31708f;
      }
      .success {
        background-color: #dff0d8;
        color: #3c763d;
      }
      .warning {
        background-color: #fcf8e3;
        color: #8a6d3b;
      }
      .error {
        background-color: #f2dede;
        color: #a94442;
      }
      #scheduleList {
        margin-top: 15px;
      }
      .schedule-item {
        background-color: #f9f9f9;
        border-left: 4px solid #3498db;
        padding: 10px;
        margin-bottom: 10px;
        border-radius: 4px;
      }
      .schedule-time {
        font-weight: bold;
        color: #2c3e50;
      }
      .notification-sound {
        margin-top: 15px;
      }
      .notification-sound button {
        margin: 5px;
      }
      .progress-container {
        margin-top: 20px;
      }
      .progress-bar {
        height: 20px;
        background-color: #ecf0f1;
        border-radius: 10px;
        overflow: hidden;
      }
      .progress {
        height: 100%;
        background-color: #3498db;
        width: 0%;
        transition: width 0.3s;
      }
      .progress-text {
        text-align: center;
        margin-top: 5px;
        font-size: 14px;
      }
    </style>
  </head>
  <body>
    <h1>学习计划助手</h1>

    <div class="section" id="scheduleSection">
      <h2>1. 安排学习时间段</h2>
      <div class="form-group">
        <label for="startTime">开始时间 (HH:MM)</label>
        <input type="time" id="startTime" value="09:00" />
      </div>
      <div class="form-group">
        <label for="endTime">结束时间 (HH:MM)</label>
        <input type="time" id="endTime" value="11:00" />
      </div>
      <div class="form-group">
        <label for="studyContent">学习内容</label>
        <textarea
          id="studyContent"
          rows="3"
          placeholder="输入这个时间段的学习内容..."
        ></textarea>
      </div>
      <button id="addScheduleButton">添加时间段</button>

      <div id="scheduleList">
        <!-- 学习时间段将在这里显示 -->
      </div>
    </div>

    <div class="section" id="reminderSection">
      <h2>2. 随机提示音设置</h2>
      <div class="form-group">
        <label for="randomMin">随机提示最小时间间隔 (分钟)</label>
        <input type="number" id="randomMin" value="3" min="1" max="30" />
      </div>
      <div class="form-group">
        <label for="randomMax">随机提示最大时间间隔 (分钟)</label>
        <input type="number" id="randomMax" value="5" min="1" max="60" />
      </div>
      <button id="testRandomSound">测试随机提示音</button>
    </div>

    <div class="section" id="pomodoroSection">
      <h2>3. 90分钟学习休息提示</h2>
      <div class="form-group">
        <label for="studyInterval">学习间隔时间 (分钟)</label>
        <input type="number" id="studyInterval" value="90" min="10" max="180" />
      </div>
      <div class="form-group">
        <label for="restInterval">休息时间 (分钟)</label>
        <input type="number" id="restInterval" value="20" min="5" max="60" />
      </div>
      <button id="testPomodoroSound">测试学习休息提示音</button>
    </div>

    <div class="section" id="controlsSection">
      <h2>控制面板</h2>
      <button id="startButton">开始</button>
      <button id="stopButton" disabled>停止</button>
      <div class="status" id="statusMessage"></div>

      <div class="progress-container">
        <div class="progress-bar">
          <div class="progress" id="progressBar"></div>
        </div>
        <div class="progress-text" id="progressText">0% 完成</div>
      </div>
    </div>

    <div class="notification-sound">
      <h3>提示音预览</h3>
      <button id="previewRandomSound">预览随机提示音</button>
      <button id="previewScheduleSound">预览学习时间段提示音</button>
      <button id="previewPomodoroSound">预览学习/休息提示音</button>
    </div>

    <script>
      // 音频上下文
      let audioContext = null
      let studyIntervalSound = null
      let randomIntervalSound = null
      let pomodoroSound = null

      // 定时器ID
      let studyTimerId = null
      let randomTimerId = null
      let pomodoroTimerId = null
      let endTimeCheckTimerId = null

      // 学习状态
      let studyStartTime = null
      let currentScheduleIndex = 0
      let isRunning = false
      let totalStudyTime = 0

      // DOM元素
      const statusMessage = document.getElementById('statusMessage')
      const startButton = document.getElementById('startButton')
      const stopButton = document.getElementById('stopButton')
      const scheduleList = document.getElementById('scheduleList')
      const progressBar = document.getElementById('progressBar')
      const progressText = document.getElementById('progressText')

      // 学习时间段数组
      let studySchedule = []
      let currentSchedule = null
      let totalTime = 0

      // 显示消息函数
      function showMessage(message, type) {
        statusMessage.textContent = message
        statusMessage.className = type
        statusMessage.style.display = 'block'

        setTimeout(() => {
          statusMessage.style.display = 'none'
        }, 3000)
      }

      // 初始化音频
      function initializeAudio() {
        audioContext = new (window.AudioContext || window.webkitAudioContext)()
      }

      // 播放学习时间段结束提示音
      function playScheduleSound() {
        if (!audioContext) {
          initializeAudio()
        }

        const oscillator = audioContext.createOscillator()
        const gainNode = audioContext.createGain()

        oscillator.connect(gainNode)
        gainNode.connect(audioContext.destination)

        oscillator.type = 'sine'
        oscillator.frequency.value = 500
        gainNode.gain.value = 0.3

        oscillator.start()

        // 播放0.5秒
        setTimeout(() => {
          oscillator.stop()
        }, 500)

        showMessage('学习时间段结束', 'success')
      }

      // 播放随机提示音
      function playRandomSound() {
        if (!audioContext) {
          initializeAudio()
        }

        const oscillator = audioContext.createOscillator()
        const gainNode = audioContext.createGain()

        oscillator.connect(gainNode)
        gainNode.connect(audioContext.destination)

        oscillator.type = 'triangle'
        oscillator.frequency.value = 600
        gainNode.gain.value = 0.3

        oscillator.start()

        // 播放0.3秒
        setTimeout(() => {
          oscillator.stop()
        }, 300)

        showMessage('随机提示音', 'info')
      }

      // 播放学习/休息提示音
      function playPomodoroSound() {
        if (!audioContext) {
          initializeAudio()
        }

        const oscillator = audioContext.createOscillator()
        const gainNode = audioContext.createGain()

        oscillator.connect(gainNode)
        gainNode.connect(audioContext.destination)

        oscillator.type = 'sawtooth'
        oscillator.frequency.value = 700
        gainNode.gain.value = 0.3

        oscillator.start()

        // 播放0.4秒
        setTimeout(() => {
          oscillator.stop()
        }, 400)

        showMessage('学习/休息提示', 'warning')
      }

      // 添加学习时间段
      document
        .getElementById('addScheduleButton')
        .addEventListener('click', function () {
          const startTime = document.getElementById('startTime').value
          const endTime = document.getElementById('endTime').value
          const studyContent = document.getElementById('studyContent').value

          if (!startTime || !endTime || !studyContent) {
            showMessage('请填写完整的学习时间段和内容', 'error')
            return
          }

          // 解析时间
          const startParts = startTime.split(':')
          const endParts = endTime.split(':')

          const startHour = parseInt(startParts[0])
          const startMinute = parseInt(startParts[1])
          const endHour = parseInt(endParts[0])
          const endMinute = parseInt(endParts[1])

          // 创建日期对象用于计算
          const now = new Date()
          const startDate = new Date(
            now.getFullYear(),
            now.getMonth(),
            now.getDate(),
            startHour,
            startMinute
          )
          const endDate = new Date(
            now.getFullYear(),
            now.getMonth(),
            now.getDate(),
            endHour,
            endMinute
          )

          // 计算时间差（分钟）
          const duration = (endDate - startDate) / 60000

          if (duration <= 0) {
            showMessage('结束时间必须晚于开始时间', 'error')
            return
          }

          // 添加到数组
          studySchedule.push({
            start: startTime,
            end: endTime,
            content: studyContent,
            duration: duration
          })

          // 显示在列表中
          const item = document.createElement('div')
          item.className = 'schedule-item'
          item.innerHTML = `
                <div class="schedule-time">${startTime} - ${endTime}</div>
                <div>${studyContent}</div>
                <button onclick="deleteSchedule(${studySchedule.length - 1})">删除</button>
            `
          scheduleList.appendChild(item)

          showMessage('学习时间段已添加', 'success')

          // 清空表单
          document.getElementById('studyContent').value = ''
        })

      // 删除学习时间段
      function deleteSchedule(index) {
        if (studySchedule[index]) {
          studySchedule.splice(index, 1)
          // 更新显示
          scheduleList.innerHTML = ''
          studySchedule.forEach((schedule, index) => {
            const item = document.createElement('div')
            item.className = 'schedule-item'
            item.innerHTML = `
                        <div class="schedule-time">${schedule.start} - ${schedule.end}</div>
                        <div>${schedule.content}</div>
                        <button onclick="deleteSchedule(${index})">删除</button>
                    `
            scheduleList.appendChild(item)
          })
          showMessage('学习时间段已删除', 'info')
        }
      }

      // 测试随机提示音
      document
        .getElementById('testRandomSound')
        .addEventListener('click', playRandomSound)

      // 测试学习休息提示音
      document
        .getElementById('testPomodoroSound')
        .addEventListener('click', playPomodoroSound)

      // 预览提示音
      document
        .getElementById('previewRandomSound')
        .addEventListener('click', playRandomSound)
      document
        .getElementById('previewScheduleSound')
        .addEventListener('click', playScheduleSound)
      document
        .getElementById('previewPomodoroSound')
        .addEventListener('click', playPomodoroSound)

      // 开始按钮
      startButton.addEventListener('click', function () {
        if (studySchedule.length === 0) {
          showMessage('请至少添加一个学习时间段', 'error')
          return
        }

        isRunning = true
        startButton.disabled = true
        stopButton.disabled = false
        showMessage('学习计划已启动', 'success')

        // 初始化音频
        initializeAudio()

        // 重置计时器
        studyStartTime = null
        currentScheduleIndex = 0
        totalStudyTime = 0
        totalTime = studySchedule.reduce(
          (total, schedule) => total + schedule.duration,
          0
        )
        clearInterval(studyTimerId)
        clearTimeout(randomTimerId)
        clearTimeout(pomodoroTimerId)
        clearTimeout(endTimeCheckTimerId)

        // 开始检查学习时间段
        startStudySchedule()

        // 开始随机提示音
        startRandomReminders()

        // 开始学习休息提示
        startPomodoroTimer()
      })

      // 停止按钮
      stopButton.addEventListener('click', function () {
        isRunning = false
        startButton.disabled = false
        stopButton.disabled = true
        showMessage('学习计划已停止', 'info')

        // 停止所有定时器
        clearInterval(studyTimerId)
        clearTimeout(randomTimerId)
        clearTimeout(pomodoroTimerId)
        clearTimeout(endTimeCheckTimerId)
        studyStartTime = null

        // 重置进度条
        progressBar.style.width = '0%'
        progressText.textContent = '0% 完成'
      })

      // 开始检查学习时间段
      function startStudySchedule() {
        studyTimerId = setInterval(checkStudySchedule, 1000)
      }

      // 检查当前是否在学习时间段内
      function checkStudySchedule() {
        if (!isRunning) return

        const now = new Date()
        const currentHour = now.getHours()
        const currentMinute = now.getMinutes()

        // 格式化当前时间为字符串
        const currentTime = `${String(currentHour).padStart(2, '0')}:${String(currentMinute).padStart(2, '0')}`

        // 检查每个时间段
        studySchedule.forEach((schedule, index) => {
          if (currentTime >= schedule.start && currentTime < schedule.end) {
            // 如果当前学习时间段改变
            if (!currentSchedule || currentSchedule.index !== index) {
              currentSchedule = { ...schedule, index }
              studyStartTime = new Date() // 重置学习开始时间

              // 计算进度条总宽度
              progressBar.style.width = `${(totalStudyTime / totalTime) * 100}%`
              progressText.textContent = `${Math.floor((totalStudyTime / totalTime) * 100)}% 完成`

              // 设置结束时间检查
              if (endTimeCheckTimerId) {
                clearTimeout(endTimeCheckTimerId)
              }

              const endTime = new Date()
              const endTimeParts = schedule.end.split(':')
              endTime.setHours(parseInt(endTimeParts[0]))
              endTime.setMinutes(parseInt(endTimeParts[1]))
              endTime.setSeconds(0)

              const timeUntilEnd = endTime - now
              if (timeUntilEnd > 0) {
                endTimeCheckTimerId = setTimeout(() => {
                  if (isRunning) {
                    playScheduleSound()
                    totalStudyTime += schedule.duration
                    // 更新进度条
                    progressBar.style.width = `${(totalStudyTime / totalTime) * 100}%`
                    progressText.textContent = `${Math.floor((totalStudyTime / totalTime) * 100)}% 完成`

                    // 检查是否所有时间段都完成
                    if (totalStudyTime >= totalTime) {
                      clearInterval(studyTimerId)
                      clearTimeout(randomTimerId)
                      clearTimeout(pomodoroTimerId)
                      clearTimeout(endTimeCheckTimerId)
                      startButton.disabled = false
                      stopButton.disabled = true
                      showMessage('所有学习时间段已完成！', 'success')
                    }
                  }
                }, timeUntilEnd)
              }
            }
          }
        })
      }

      // 开始随机提醒
      function startRandomReminders() {
        if (!isRunning) return

        const minInterval = document.getElementById('randomMin').value * 60000 // 转换为毫秒
        const maxInterval = document.getElementById('randomMax').value * 60000

        const randomInterval =
          Math.floor(Math.random() * (maxInterval - minInterval + 1)) +
          minInterval

        randomTimerId = setTimeout(() => {
          if (isRunning) {
            playRandomSound()
            startRandomReminders()
          }
        }, randomInterval)
      }

      // 开始学习休息定时器
      function startPomodoroTimer() {
        if (!isRunning) return

        const studyInterval =
          document.getElementById('studyInterval').value * 60000 // 转换为毫秒
        const restInterval =
          document.getElementById('restInterval').value * 60000

        if (studyStartTime) {
          // 计算已经学习的时间
          const currentTime = new Date()
          const elapsedStudyTime = (currentTime - studyStartTime) / 1000 // 秒

          // 检查是否达到学习间隔时间
          if (elapsedStudyTime >= studyInterval) {
            // 播放休息提示音
            playPomodoroSound()
            showMessage(
              `休息时间到！请休息${document.getElementById('restInterval').value}分钟`,
              'warning'
            )

            // 设置休息计时器
            pomodoroTimerId = setTimeout(() => {
              if (isRunning) {
                // 播放学习提示音
                playPomodoroSound()
                showMessage('休息时间结束，继续学习！', 'success')
                studyStartTime = new Date() // 重置学习开始时间
                startPomodoroTimer()
              }
            }, restInterval)
          } else {
            // 继续计时
            setTimeout(startPomodoroTimer, 1000)
          }
        } else {
          setTimeout(startPomodoroTimer, 1000)
        }
      }
    </script>
  </body>
</html>
